package com.cskaoyan.javase.io._1byte._3filecopy;

import org.junit.Test;

import java.io.*;

/**
 * 基于FileOutputStream和FileInputStream实现文件的复制功能
 * 核心的思路就是一边(循环)读一边(循环)写
 *
 * @since 16:57
 * @author wuguidong@cskaoyan.onaliyun.com
 */
public class Demo {
    @Test
    public void copySingleByte() throws IOException {
        // 一个字节一个字节的读,并写入
        // 1.分别创建输入/输出流对象
        FileInputStream in = new FileInputStream("E:\\1\\新垣结衣.jpg");
        FileOutputStream out = new FileOutputStream("E:\\1\\新垣结衣copy.jpg");
        // 2.循环读,然后循环写
        int readData;
        while ((readData = in.read()) != -1) {
            // 循环写
            out.write(readData);
        }
        // 3.关闭流
        in.close();
        out.close();
    }


    @Test
    public void copyMultiByte() throws IOException {
        // 一个字节数组一个字节数组的读,并写入
        // 1.分别创建输入/输出流对象
        FileInputStream in = new FileInputStream("E:\\1\\1.mp4");
        FileOutputStream out = new FileOutputStream("E:\\1\\1copy.mp4");
        // 2.循环读,然后循环写
        int readCount;
        byte[] buf = new byte[1024];
        while ((readCount = in.read(buf)) != -1) {
            // 循环写
            out.write(buf, 0, readCount);
        }
        // 3.关闭流
        in.close();
        out.close();
    }

    @Test
    public void copyMultiBuffer() throws IOException {
        // 一个字节数组一个字节数组的读,并写入
        // 1.分别创建输入/输出流对象
        BufferedInputStream in = new BufferedInputStream(new FileInputStream("E:\\1\\1.mp4"));
        BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream("E:\\1\\1copy.mp4"));
        // 2.循环读,然后循环写
        int readCount;
        byte[] buf = new byte[1024];
        while ((readCount = in.read(buf)) != -1) {
            // 循环写
            out.write(buf, 0, readCount);
        }
        // 3.手动刷新
        out.flush();
        // 4.关闭流
        in.close();
        out.close();
    }

}
